package models

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"strings"
	"time"
	"zbn-oil-consumption/config"
	"zbn-oil-consumption/utils"
)

type Admin struct {
	Id        int64     `bson:"_id" json:"id"`
	Username  string    `bson:"username" json:"username"`
	Nickname  string    `bson:"nickname" json:"nickname"`
	Password  string    `bson:"password" json:"password"`
	Status    int       `bson:"status" json:"status"`
	LastLogin time.Time `bson:"last_login" json:"lastLogin"`
	CreatedAt time.Time `bson:"created_at" json:"createdAt"`
}

func (Admin) Add(Admin Admin) (id interface{}, err error) {
	ctx := context.Background()
	c := config.Db.Collection("admins")
	Admin.Id = time.Now().Unix()
	res, err := c.InsertOne(ctx, Admin)
	if err != nil {
		return
	}
	id = res.InsertedID
	return
}

func (Admin) Update(data Admin) (id int64, err error) {
	ctx := context.Background()
	c := config.Db.Collection("admins")
	filter := bson.M{"_id": data.Id}
	update := bson.M{
		"$set": bson.M{
			"username": data.Username,
			"nickname": data.Nickname,
			"password": data.Password,
			"status":   data.Status,
		},
	}
	res, err := c.UpdateOne(ctx, filter, update)
	if err != nil {
		return
	}
	id = res.ModifiedCount
	return
}

func (Admin) ChangeStatus(data Admin) (id int64, err error) {
	ctx := context.Background()
	c := config.Db.Collection("admins")
	filter := bson.M{"_id": data.Id}
	update := bson.M{
		"$set": bson.M{
			"status": data.Status,
		},
	}
	res, err := c.UpdateOne(ctx, filter, update)
	if err != nil {
		return
	}
	id = res.ModifiedCount
	return
}

func (Admin) Delete(data Admin) (id int64, err error) {
	ctx := context.Background()
	c := config.Db.Collection("admins")
	filter := bson.M{"_id": data.Id}
	res, err := c.DeleteOne(ctx, filter)
	if err != nil {
		return
	}
	id = res.DeletedCount
	return
}

func (Admin) FindByUsername(username string) (Admin, error) {
	ctx := context.Background()
	var res Admin
	filter := bson.M{"username": username}
	err := config.Db.Collection("admins").FindOne(ctx, filter).Decode(&res)
	return res, err
}

func (Admin) GetList(params utils.Params) (total int64, res []Admin, err error) {
	ctx := context.Background()
	skip := (params.Page - 1) * params.PageSize
	findOptions := options.Find()
	findOptions.SetSkip(int64(skip))
	findOptions.SetLimit(int64(params.PageSize))
	filter := bson.M{}
	if strings.TrimSpace(params.Username) != "" {
		filter["username"] = strings.TrimSpace(params.Username)
	}
	c := config.Db.Collection("admins")
	total, err = c.CountDocuments(ctx, filter)
	if err != nil {
		return 0, nil, err
	}
	// 执行查询
	cursor, err := c.Find(ctx, filter, findOptions)
	if err != nil {
		return 0, nil, fmt.Errorf("find failed: %w", err)
	}
	defer cursor.Close(ctx)
	err = cursor.All(ctx, &res)
	return
}
